﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using ScrumTable.Common;
using ScrumTable.Common.FileSystem;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Net;
using ScrumTable.Common.Security;
using ScrumTable.DL.Data.Schema;
using ScrumTable.DL.Data.TFS.Properties;
using ScrumTable.DL.Data.TFS.Services.Reporting.ReportService;

#endregion

namespace ScrumTable.DL.Data.TFS.Services.FileSystem
{
    /// <summary>
    /// This class contains a set of functionalities which are used to
    /// connect to the file system data serialization.
    /// </summary>
    public class FsContext
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private const string XmlDataExtension = "_Data.xml";
        private const string DataPathSchemaAttribute = "DataPath"; 
        private readonly IDictionary<SchemaBase, DataBucket> _serializationData = new Dictionary<SchemaBase, DataBucket>();
        
        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new FsContext instance. This constructor is used in
        /// the current library only.
        /// </summary>
        public FsContext()
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the deserialized data from associated to the specified 
        /// schema.
        /// </summary>
        /// <param name="schema">Specifies the schema which contain the path information.</param>
        /// <returns>Returns the deserialized and cached data object.</returns>
        public T GetData<T>(SchemaBase schema)
            where T : new()
        {
            PreCondition.AssertNotNull(schema, "schema");

            return (T)(RetrieveData<T>(schema).Data);
        }

        /// <summary>
        /// Stores the given data object to store back into the data cache
        /// and to the file system.
        /// </summary>
        /// <typeparam name="T">Specifies the element to store.</typeparam>
        /// <param name="schema">Specifies the schema which contain the path information.</param>
        /// <param name="dataToStore">Specifies the object to serialize.</param>
        public void SetData<T>(SchemaBase schema, T dataToStore)
            where T : new()
        {
            PreCondition.AssertNotNull(schema, "schema");
            PreCondition.AssertNotNull(dataToStore, "dataToStore");

            StoreData(
                RetrieveData<T>(schema),
                dataToStore);
        }

        private DataBucket RetrieveData<T>(SchemaBase schema)
            where T : new()
        {
            if (!_serializationData.ContainsKey(schema))
            {
                string path = GetPathFromSchema(schema);

                _serializationData[schema] = new DataBucket
                                                 {
                                                     Data = DeserializeFrom<T>(path),
                                                     Path = path
                                                 };
            }
            return _serializationData[schema];
        }
        
        private string GetPathFromSchema(SchemaBase schema)
        {
            if (schema.SchemaProperties.ContainsKey(DataPathSchemaAttribute))
            {
                string path = schema.SchemaProperties[DataPathSchemaAttribute];

                if (DirectoryUtil.TryCreate(Path.GetDirectoryName(path)))
                {
                    return path;
                }
            }
            return Path.Combine(DataFolderUtil.GetDataPath(), schema.SchemaName + XmlDataExtension);
        }

        private void StoreData<T>(DataBucket dataBucket, T toSet)
        {
            string directoryPath = Path.GetDirectoryName(dataBucket.Path);
 
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            dataBucket.Data = toSet;
            SerializeTo(dataBucket.Path, toSet);
        }


        //--------------------------------------------------------------------
        // Serialization Facilities
        //--------------------------------------------------------------------

        private void SerializeTo<T>(string storagePath, T toSerialize)
        {
            if (!File.Exists(storagePath))
            {
                using (var file = new FileStream(storagePath, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    CreateSerializer<T>().Serialize(file, toSerialize);
                }
            }
            else
            {
                using (var file = new FileStream(storagePath, FileMode.Truncate, FileAccess.Write, FileShare.Write))
                {
                    CreateSerializer<T>().Serialize(file, toSerialize);
                }
            }
        }

        private T DeserializeFrom<T>(string storagePath)
            where T : new()
        {
            if (File.Exists(storagePath))
            {
                using (var file = new FileStream(storagePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    try
                    {
                        return (T)CreateSerializer<T>().Deserialize(file);
                    }
                    catch (Exception e)
                    {
                        Logger<FsContext>.Error(
                            string.Format(Resources.ExcRsCtxFileReadError, storagePath),
                            e);
                    }
                }
            }
            return new T();
        }

        private XmlSerializer CreateSerializer<T>()
        {
            return new XmlSerializer(typeof(T));
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion



        //--------------------------------------------------------------------
        // Nested Classes
        //--------------------------------------------------------------------

        internal class DataBucket
        {
            internal string Path { get; set; }
            internal object Data { get; set; }
        }
    }
}
